<template>
  <a-modal :open="open" :width="960" title="模版选择" centered :ok-button-props="{ disabled: !isCompleted }" @ok="initTemplate" @cancel="onCancel">
    <div class="flex justify-between overflow-y-auto h-[56vh]">
      <div class="w-60 h-full overflow-y-scroll">
        <a-directory-tree
          v-if="treeData.length"
          v-model:selected-keys="selectedKeys"
          class="h-full"
          :tree-data="treeData"
          default-expand-all
          :field-names="{ key: 'id' }"
        >
          <template #icon="{ template }">
            <img v-if="template" :src="IconDocument" width="14" class="pb-1" />
            <img v-else :src="IconDirectory" width="14" class="pb-1" />
          </template>
          <template #title="item">
            <div class="flex justify-between" @click="selectTree(item.id, item.children, item.templateId)">
              <div class="mr-4 truncate">{{ item.categoryName }}</div>
            </div>
          </template>
        </a-directory-tree>
      </div>
      <a-divider type="vertical" class="h-full w-4" />
      <div class="h-full flex-1 flex flex-col">
        <a-form ref="formRef" class="form-style-flex" :model="formState" :label-col="{ style: { width: '80px' } }">
          <a-form-item name="documentFileName" label="病历名称" v-bind="validateInfos.documentFileName">
            <a-input v-model:value="formState.documentFileName" placeholder="请输入病历名称" />
          </a-form-item>
          <a-form-item name="zjm" label="" class="ml-4">
            <a-input-search v-model:value="formState.zjm" placeholder="模版名称/助记码" style="width: 200px" @search="getTemplateData()" />
          </a-form-item>
        </a-form>
        <a-tabs v-model:active-key="tabsKey" destroy-inactive-tab-pane @change="onChangeTabs">
          <a-tab-pane key="2" tab="科室" />
          <a-tab-pane key="1" tab="个人" />
          <a-tab-pane key="3" tab="全院" />
          <a-tab-pane key="0" tab="全部" />
        </a-tabs>
        <div v-if="!templateData.length" class="flex-1 overflow-y-auto">
          <a-empty description="暂无数据" />
        </div>
        <div v-else class="flex-1 overflow-y-auto">
          <div
            v-for="(item, index) in templateData"
            :key="index"
            class="w-full bg-gray-100 mb-2 rounded py-4 px-4 cursor-pointer border border-transparent hover:bg-secondary"
            :class="{ active: item.templateId === selectItem.templateId }"
            @click="selectTemplate(item)"
          >
            <div class="flex justify-between">
              <div class="text-primary">{{ item.templateName }}</div>
              <div>
                <span v-if="item.isFirst === '1'" class="mr-3">初诊</span>
                <span v-if="item.isFirst === '2'" class="mr-3">不限</span>
                <span v-if="item.isFirst === '0'" class="mr-3">复诊</span>
                <span v-if="item.sexRange === '0'" class="inline-block w-8 text-right">不限</span>
                <span v-if="item.sexRange === '1'" class="inline-block w-8 text-right">男</span>
                <span v-if="item.sexRange === '2'" class="inline-block w-8 text-right">女</span>
              </div>
            </div>
            <div v-if="item.memo" class="mt-4">{{ item.memo }}</div>
          </div>
        </div>
      </div>
    </div>
  </a-modal>
</template>
<script setup>
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import IconDirectory from '@/assets/icons/icon-directory.svg'
import IconDocument from '@/assets/icons/icon-document.svg'

const props = defineProps({
  open: Boolean,
  currentPatient: {
    type: Object,
    default: () => ({})
  },
  categroyType: {
    type: String,
    default: '1'
  }
})
const emit = defineEmits(['update:open', 'success'])
const treeData = ref([])
const selectedKeys = ref(['0-0-0', '0-0-1'])
const tabsKey = ref('2')
const menuId = ref('')
const tempId = ref('')
const formState = ref({
  documentFileName: '',
  zjm: ''
})
const selectItem = ref({})
const allTemplateData = ref([])
const templateData = ref([])
const rulesState = ref({
  documentFileName: [{ required: true, message: '请输入病历名称' }]
})
const { isCompleted, validateInfos, resetFields } = useForm(formState, rulesState)

const getLeftTreeData = async () => {
  const { code, data, msg } = await post('/emr/emrCategory/getEmrCategoryByTree', {
    categroyType: props.categroyType,
    status: 1
  })
  if (code !== 0) return message.error(msg)
  const templateData = data ? data : []
  treeData.value = filterNodesByTemplate(templateData)
}
const selectTree = (id, children, templateId) => {
  if (children.length > 0) return
  menuId.value = id
  tempId.value = templateId
  getTemplateData()
}
const dataSource = ref([])
const getTemplateData = async () => {
  const { code, data, msg } = await post(`/emr/emrTemplate/getAllEmrTempletesByCategoryId`, {
    categroyType: props.categroyType,
    categoryId: menuId.value,
    zjm: formState.value.zjm
  })
  if (code !== 0) return message.error(msg)
  allTemplateData.value = data || []
  templateData.value = data || []
  dataSource.value = data || []
}
const initTemplate = async () => {
  const { data, code, msg } = await post(
    'emr/patientEmrDocument/doInitEmrDocument',
    {
      categroyType: props.categroyType,
      brId: props.currentPatient.brId,
      jzbh: props.currentPatient.jzbh,
      templateId: selectItem.value.templateId
    },
    {
      loading: true
    }
  )
  if (code !== 0) return message.error(msg)
  if (!data) return message.error('初始化失败')
  saveCategory(data)
}
const saveCategory = async (params) => {
  const { code, msg, data } = await post('/emr/patientEmrDocument/savePatientEmrDocument', {
    brId: props.currentPatient.brId,
    categroyId: menuId.value,
    documentFileName: formState.value.documentFileName,
    xml: params,
    lsh: props.currentPatient.inplsh,
    categroyType: props.categroyType,
    templateId: selectItem.value.templateId
  })
  if (code !== 0) return message.error(msg)
  message.success(msg || '操作成功')
  emit('update:open', false)
  emit('success', data)
}
const selectTemplate = (item) => {
  selectItem.value = item
  formState.value.documentFileName = dayjs().format('YYYY-MM-DD') + ' ' + item.templateName
}
// 过滤掉 template 字段为 true 的节点及其子节点
const filterNodesByTemplate = (nodes) => {
  const filteredNodes = []
  nodes.forEach((node) => {
    if (node.template === true) {
      return
    }
    if (node.children && node.children.length > 0) {
      node.children = filterNodesByTemplate(node.children)
    }
    filteredNodes.push(node)
  })

  return filteredNodes
}
const onCancel = () => {
  formState.value.documentFileName = ''
  formState.value.zjm = ''
  selectItem.value = {}
  emit('update:open', false)
}
const onChangeTabs = () => {
  // getTemplateData()
  if (tabsKey.value === '0') {
    templateData.value = dataSource.value
  } else {
    templateData.value = dataSource.value.filter((item) => item.usableRange === tabsKey.value)
  }
}
watch(
  () => props.open,
  (val) => {
    if (val) {
      getLeftTreeData()
    } else {
      selectedKeys.value = []
      menuId.value = ''
      tempId.value = ''
      allTemplateData.value = []
      templateData.value = []
      dataSource.value = []
      formState.value = {
        documentFileName: '',
        zjm: ''
      }
      resetFields()
    }
  }
)
</script>
<style lang="less" scoped>
.active {
  background-color: var(--secondary-color);
  border: 1px solid var(--primary-color);
}
:deep(.ant-tree-treenode) {
  display: flex;
  width: 100%;
  padding: 8px 0;

  &:before {
    bottom: 0 !important;
  }
  .ant-tree-node-content-wrapper {
    display: flex;
    align-items: center;
    .ant-tree-title {
      flex: 1;
    }
  }
}
</style>
